import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/pages/Login'
import Home from '@/pages/Home'
import Content1 from '@/pages/Home/Content1'
import Content2 from '@/pages/Home/Content2'
import Content3 from '@/pages/Home/Content3'
Vue.use(VueRouter)

// #region 解决路由的多次跳转
// 先把VueRouter原型对象的push，先保存一份
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace

// 重写push|replace
// 第一个参数：告诉原来push方法，你往哪里跳转（传递哪些参数）
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    // call||apply区别
    // 相同点，都可以调用函数一次，都可以篡改函数的上下文一次
    // 不同点：call与apply传递参数：call传递参数用逗号隔开，apply方法执行，传递数组
    originPush.call(this, location, resolve, reject)
  } else {
    // push方法没有产地第二个参数|第三个参数
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
// 重写VueRouter.prototype身上的replace方法了
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
// #endregion

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login, meta: { isAuth: true, title: '登入页面' } },
  {
    path: '/home',
    component: Home,
    meta: { title: '首页' },
    children: [
      { path: 'content1', component: Content1, meta: { title: '内容页面1' } },
      { path: 'content2', component: Content2, meta: { title: '内容页面2' } },
      { path: 'content3', component: Content3, meta: { title: '内容页面3' } }
    ],
    redirect: '/home/content1'
  }
]

const router = new VueRouter({
  routes,
  // 滚动行为
  scrollBehavior (to, from, savedPosition) {
    // 返回的这个y=0，代表的滚动条在最上方
    return { y: 0 }
  }
})

// 后置路由守卫展示页面标题
router.afterEach((to, from) => {
  document.title = to.meta.title || '江西制作系统'
})

// 前置路由守卫，判断用户是否登入
/* router.beforeEach((to, form, next) => {
  console.log('前置路由守卫', to, form)
  if (to.meta.isAuth) {
    // 判断是否需要权限
    if (localStorage.getItem('school') === 'jxzz') {
      next()
    } else {
      alert('学习名不对，无权查看！')
    }
  } else {
    next()
  }
}) */

export default router
